<?php
/**
 * 数据库操作类
 */
namespace m;
class dbo extends \i{
    private static $_i;
    public $db;
    public $dbpars=[];
    public $pdopars=[];
    public $tmpsql='';
    public static function i($pars=[]){
        self::$_i=new \m\dbo($pars);
        self::$_i->dbpars=[];
        return self::$_i;
    }
    public function __construct($pars=[]){
        parent::__construct($pars);
        $this->db=\lib\db::i(\i::commconf('db'));
    }
    /**
     * table("table_name")
     * */
    public function table($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
    where("a=1 and b>2 or c>3")
     */
    public function where($pars)
    {
        $pars and $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
    where 数组
     */
    public function whereary($pars)
    {
        $pars and $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * orderby("id asc, user desc ")
     */
    public function orderby($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * limit(1,10) 在select的时候
     * limit(10) 在insert del update 的时候
     * */
    public function limit($p1='',$p2='')
    {
        $pars=" $p1 ";
        $p2 and $pars=" $p1,$p2 ";
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * groupby("col_name1,col_name2")
     */
    public function groupby($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * 
     * insert($arys)
     * $arys=[
     * [
     * 'uid'=12,
     * 'uname'='n1',
     * ],
     * [
     * 'uid'=13,
     * 'uname'='n2',
     * ],
     * ];
     * */
    public function insert_data($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * ignore
     */
    public function ignore()
    {
        $this->dbpars[__FUNCTION__]=' ignore ';
        return $this;
    }
    /**
     * cols('uid,uname as name') 设置在select中的col项目
     * */
    public function cols($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;
        return $this;
    }
    /**
     * sets($ary)
     * $ary=['id'=12,'name'='name1'];
     * */
    public function sets($pars)
    {
        $this->dbpars[__FUNCTION__]=$pars;

        return $this;
    }
    
    public function stusql($type)
    {
        $tmpsql="";
        $table="";
        isset($this->dbpars['table']) and $table=$this->dbpars['table'];
        strstr($table,' ') and $table='('.$table.')';
        $groupby="";
        isset($this->dbpars['groupby']) and $groupby=" group by ".$this->dbpars['groupby'];
        $orderby='';
        isset($this->dbpars['orderby']) and $orderby=" order by ".$this->dbpars['orderby'];

        $limit="";
        isset($this->dbpars['limit']) and $limit=" limit ".$this->dbpars['limit'];
        
        $insert_val='';
        $insert_col='';
        if(isset($this->dbpars["insert_data"]))
        {
            $this->pdopars=$this->dbpars['insert_data'];
            $first_ele=current($this->dbpars['insert_data']);
            $col_k_ary=array_keys($first_ele);
            $col_v_ary=[];
            //组合pdo数据
            $insert_col="(".implode(',',$col_k_ary).")";
            foreach($col_k_ary as $k=>$v)
            {
                $col_v_ary[$k]=":".$v;
            }
            $insert_val="(".implode(',',$col_v_ary).")";
        }

        
        $cols=' * ';
        isset($this->dbpars['cols']) and $cols=" ".$this->dbpars['cols']." ";
        $sets='';//传入参数为一个数组
        if(isset($this->dbpars['sets']))
        {
            if(is_array($this->dbpars['sets']))
            {
                foreach($this->dbpars['sets'] as $k=>$v)
                {
                    $sets[]="$k=:$k";
                }
                $this->pdopars=[
                    'upd'=>$this->dbpars['sets'],
                ];
                $sets=' set '.implode(',',$sets);
            }else{
                $sets=' set '.$this->dbpars['sets'];
            }
        }
        $ignore='';
        isset($this->dbpars['ignore']) and $ignore=" ignore ";
        $ignore='ignore';

        $where='';
        $whereary=[];
//        \c\tool::dug($this->dbpars);
        if(isset($this->dbpars['whereary']))
        {
            if(is_array($this->dbpars['whereary']))
            {
                foreach($this->dbpars['whereary'] as $k=>$v)
                {
                    $tag=substr($v,0,1);
                    if($tag=="%")
                    {
                        $whereary[]="$k like :$k";
                        $this->dbpars['whereary'][$k]="%".substr($v,1)."%";
                    }elseif($tag==">")
                    {
                        $whereary[]="$k>:$k";
                        $this->dbpars['whereary'][$k]=substr($v,1);
                    }elseif($tag=="<")
                    {
                        $whereary[]="$k<:$k";
                        $this->dbpars['whereary'][$k]=substr($v,1);
                    }elseif($tag=="!"){
                        $whereary[]="$k!=:$k";
                        $this->dbpars['whereary'][$k]=substr($v,1);
                    }else{
                        $whereary[]="$k=:$k";
                    }
                }
                if($this->pdopars)
                {
                    foreach($this->pdopars as $k=>$v)
                    {
                        $this->pdopars[$k]=array_merge($this->pdopars[$k],$this->dbpars['whereary']);
                    }
                }else{
                $this->pdopars=[
                    'sel'=>$this->dbpars['whereary'],
                ];
                }
//                \c\tool::dug($this->pdopars,'inpreser');
                $where=' where '.implode(' and ',$whereary);
            }else{
                $where=' where '.$this->dbpars['sets'];
            }
        }

        if(isset($this->dbpars['where']))
        {
            $where=" where ".$this->dbpars['where'];
            if($this->pdopars)
            {

            }else{
                $this->pdopars=[
                    'sel'=>[],
                ];
            }
        }


        switch ($type){
            case 'select':
            $tmpsql="select {$cols} from $table {$where} {$groupby} {$orderby} {$limit}";
            break;
            case 'update':
            $tmpsql="update {$table} {$sets} {$where} {$orderby} {$limit}";
            break;
            case 'insert':
            $tmpsql="insert {$ignore} into {$table} {$insert_col} values {$insert_val}";
            break;
            case 'delete':
            $tmpsql="delete from {$table} {$where} {$orderby} {$limit}";
            break;
            default:
            $tmpsql="no type";
            break;
        }
        $this->tmpsql=$tmpsql;
        return $this->tmpsql;
    }
    public function sql($type='')
    {
        $dbtmp=[
                "sql"=>$this->stusql($type),
                "pars"=>$this->pdopars,

        ];
        return $dbtmp;
    }
    public function select()
    {
        $sql=$this->stusql('select');
        $tmp=$this->pdopars;
        isset($tmp['sel']) or $this->pdopars=[
            'sel'=>[],
        ];
//        \c\tool::dug($this->pdopars,'inselect');
        $ret=$this->go($sql);
        $rel=&$ret['table']['sel'];
        $rel or $rel=[];
        return $rel;
    }
    public function insert()
    {
        $sql=$this->stusql('insert');
        $ret=$this->go($sql);
        return ['lastInsertId'=>$ret['_pdo_']['lastInsertId'],'rowCount'=>$ret['_pdo_']['rowCount']];
    }
    public function update()
    {
        $ret=$this->go($this->stusql('update'));
        return ['rowCount'=>$ret['_pdo_']['rowCount']];
    }
    public function delete()
    {
        $ret=$this->go($this->stusql('delete'));
        return ['rowCount'=>&$ret['_pdo_']['rowCount']];
    }
    public function setpdopars($pars=[])
    {
        $this->pdopars=$pars;
        return $this;
    }
    public function go($sql="")
    {
        $dbtmp=[
            'table'=>[
                "sql"=>$sql,
                "pars"=>$this->pdopars,
            ]
        ];
        $ret=$this->db->presql($dbtmp);
        return $ret;
    }
    //构建多表查询中的表字段
    public function gettablecols($tables=[],$str=true)
    {
        //多表查询中,自动设置字段名.
        $colsret=[];
            foreach($tables as $tableas=>$tablename)
            {
                $dbtmp=[
                    'table'=>[
                        "sql"=>'show full columns from '.$tablename,
                        "pars"=>[],
                    ]
                ];
                $selret=$this->db->presql($dbtmp);
                $selret=$selret['table'][0];
                foreach($selret as $colinf)
                {
                    $colsret[$tableas][]="{$tableas}.{$colinf['Field']} as {$tableas}_{$colinf['Field']}";
                }
            }
        if($str)
        {
            foreach($colsret as $tableas=>$v)
            {
                $colsret[$tableas]=implode(',',$v);
            }
            $colsret=implode(',',$colsret);
        }else{

        }
        return $colsret;

    }
}